import compose from "./compose";

function applyMiddleware(...middleware) {
  return function (createStore) {
    return function (reducer) {
      //这个是原始的厂库
      let store = createStore(reducer);
      //抛出一个错误，防止该变量被引用，主要是定义一个变量，保存新的重写之后的dispatch方法
      let dispatch = () => {
        throw new Error("null");
      };
      //定义一个对象，主要是为了保存新的dispatch方法，并且作为参数传入到每一个中间件中
      let middlewareApi = {
        getState: store.getState,
        dispatch: (...args) => dispatch(...args),
      };
      //去掉每一个中间件的第一层
      const chain = middleware.map((item) => {
        return item(middlewareApi);
      });
      //保存新的重写之后的dispatch方法
      // 组合中间件
      dispatch = compose(...chain)(store.dispatch);
      return {
        ...store,
        dispatch,
      };
    };
  };
}

export default applyMiddleware;
